#!/usr/bin/env python2.7
# _*_ coding:UTF-8 _*_
"""
__author__ = 'shede333'

文件相关的处理
"""

import os
import common_util
import shutil
import subprocess


def _get_space_str(space_num):
    space_str = ""
    while space_num > 0:
        space_str += " "
        space_num -= 1
    return space_str


def file_name_add_2x():
    """
    为文件名增加"@2x"后缀

    :return:
    """
    dir_path = common_util.user_input_path(is_dir=True)
    file_list = os.listdir(dir_path)
    file_suffix = "@2x"
    for file_name in file_list:
        if (not os.path.isfile(os.path.join(dir_path, file_name))) or file_name.startswith("."):
            continue
        name_0, name_ext = os.path.splitext(file_name)
        if name_0.endswith(file_suffix):
            continue
        new_name = name_0 + file_suffix + name_ext
        old_file_path = os.path.join(dir_path, file_name)
        new_file_path = os.path.join(dir_path, new_name)
        print "new_path: ", new_file_path
        os.rename(old_file_path, new_file_path)


def filter_x_file(suffixes=("@2x",)):
    """
    根据指定的文件名后缀，把文件归类到各自的目录里
    :param suffixes: 文件名后缀数组（可以指定多个文件名后缀）
    :return:
    """
    dir_path = common_util.user_input_path(is_dir=True)
    file_list = os.listdir(dir_path)
    for file_name in file_list:
        name_0, name_ext = os.path.splitext(file_name)
        file_suffix = None
        for tmp_suffix in suffixes:
            if name_0.endswith(tmp_suffix):
                file_suffix = tmp_suffix
                break
        if file_suffix is not None:
            new_dir_path = os.path.join(dir_path, file_suffix)
            if not os.path.isdir(new_dir_path):
                os.mkdir(new_dir_path)
            new_file_path = os.path.join(new_dir_path, file_name)
            old_file_path = os.path.join(dir_path, file_name)
            if (not os.path.exists(new_file_path)) and os.path.isfile(old_file_path):
                shutil.copy(old_file_path, new_file_path)
    command = "open " + dir_path
    subprocess.call(command, shell=True)


def rename(name_contain_ext=False):
    """
    重命名文件，给文件名增加前缀、后缀
    :param name_contain_ext: 文件名是否包含扩展名，默认False
    :return:
    """
    dir_path = common_util.user_input_path(is_dir=True)
    file_list = common_util.file_list_in_dir(dir_path, is_contain_hidden_file=False,
                                             is_recursion=False)
    print "\nwill renamed file list:"

    name_prefix = raw_input("\nplease file name prefix:")
    name_suffix = raw_input("please file name suffix:")

    for file_name, file_path in file_list:
        origin_file = file_path
        new_name, ext_name = os.path.splitext(file_name)
        if name_contain_ext:
            new_name = file_name
            ext_name = ""
        if len(name_prefix) > 0:
            new_name = name_prefix + new_name
        if len(name_suffix) > 0:
            new_name += name_suffix
        new_name += ext_name

        des_file = os.path.join(dir_path, new_name)
        os.rename(origin_file, des_file)
        print "rename :%s%s\n    to :%s" % (_get_space_str(len(name_prefix)), file_name, new_name)


def sort_by_size(dir_path=None):
    """
    按照文件大小，升序打印文件列表信息（路径、大小）
    :param dir_path: 目录路径
    :return:
    """
    if (dir_path is None) or (not os.path.isdir(dir_path)):
        dir_path = common_util.user_input_path()

    file_list = common_util.file_list_in_dir(dir_path, is_recursion=True)
    print "file count:", len(file_list)

    # kb_dic = {"divisor": 1024.0, "unit": "KB"}
    mb_dic = {"divisor": 1024.0 ** 2, "unit": "MB"}
    used_unit = mb_dic
    tmp_list_1 = []
    tmp_list_10 = []
    tmp_list_100 = []
    tmp_list_more = []
    for tmp_name, tmp_path in file_list:
        file_size = os.path.getsize(tmp_path) / used_unit["divisor"]
        tmp_dic = {"name": tmp_name, "path": tmp_path, "size": file_size}
        if file_size <= 1:
            tmp_list_1.append(tmp_dic)
        elif file_size <= 10:
            tmp_list_10.append(tmp_dic)
        elif file_size <= 100:
            tmp_list_100.append(tmp_dic)
        else:
            tmp_list_more.append(tmp_dic)

    print "0~1%s :%d" % (used_unit["unit"], len(tmp_list_1))
    print "1~10%s :%d" % (used_unit["unit"], len(tmp_list_10))
    print "10~100%s :%d" % (used_unit["unit"], len(tmp_list_100))
    print "100~ %s :%d" % (used_unit["unit"], len(tmp_list_more))

    print "10~100MB:\n"
    for tmp_info in tmp_list_100:
        print tmp_info["path"], " : %.2fMB" % tmp_info["size"]

    print "100~ MB:\n"
    for tmp_info in tmp_list_more:
        print tmp_info["path"], " : %.2fMB" % tmp_info["size"]


def main():
    """
    主入口
    :return:
    """
    rename()


if __name__ == '__main__':
    main()
